package com.mhkj.revise.monthPlan.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.mhkj.base.functionOffice.entity.FunctionOffice;
import com.mhkj.base.itemInfo.item.entity.Item;
import com.mhkj.common.enums.ApplyState;
import com.mhkj.common.enums.PlanType;
import com.mhkj.common.util.ItemHelper;
import com.mhkj.revise.monthPlan.repository.PlanMonthRepository;
import com.mhkj.revise.monthPlan.service.PlanMonthService;
import com.mhkj.revise.plan.entity.PlanNode;
import com.mics.core.common.componet.Pagination;
import com.mics.core.system.base.service.impl.BaseServiceImpl;
import com.mics.core.system.organizational.bean.Company;
import com.mics.core.system.organizational.bean.Office;
import com.mics.core.system.organizational.bean.Post;
import com.mics.core.system.organizational.service.OrgService;
import com.mics.core.system.rbac.entity.Dictionary;
import com.mics.core.system.rbac.service.DictionaryService;

@Service
public class PlanMonthServiceImpl extends BaseServiceImpl<PlanNode> implements PlanMonthService {
    @Resource
    private PlanMonthRepository planMonthRepository;
    @Resource
    private OrgService orgService;
    @Resource
    private ItemHelper itemHelper;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    public void setPlanMonthRepository(PlanMonthRepository planMonthRepository) {
        super.setBaseRepository(planMonthRepository);
    }

    @Override
    public Pagination<PlanNode> keyListByPage(PlanNode planNode,String yearMonth,String startDate,String endDate,String nodeName,String dateTemp, int type, int pageIndex, int pageSize) {
        Specification<PlanNode> spec = new Specification<PlanNode> () {
            private static final long serialVersionUID = -786003485941679959L;
            @Override
            public Predicate toPredicate(javax.persistence.criteria.Root<PlanNode> root, CriteriaQuery<?> query,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> lstPredicates = new ArrayList<Predicate>();
                Join<Object, Object> plan = root.join("plan", JoinType.LEFT);
                if(StringUtils.hasText(yearMonth)){
                    try {
                        Date endDate1 = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
                        Date beginDate = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
                        Predicate p4 = criteriaBuilder.lessThanOrEqualTo(root.get("beginDate"), endDate1);
                        Predicate p5 = criteriaBuilder.greaterThanOrEqualTo(root.get("endDate"), beginDate);
                        lstPredicates.add(p4);
                        lstPredicates.add(p5);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                //判断项目权限和职能权限
                List<Item> items = itemHelper.getCurrentUserItems();
                List<FunctionOffice> functionOffices = itemHelper.getCurrentUserFunctionOffices();
                Predicate pitem = null;
                Predicate pfunction = null;
                if(itemHelper.getCurrentUserItems().size() > 0 ){
                	pitem=plan.get("item").in(items);
                }else{
                	pitem=plan.get("item").isNull();
                }
                if(itemHelper.getCurrentUserFunctionOffices().size() > 0 ){
                	 pfunction=plan.get("functionOffice").in(functionOffices);
                }else{
                	  pfunction=plan.get("functionOffice").isNull();
                }
		       lstPredicates.add(criteriaBuilder.or(pitem, pfunction));
               
		       if(StringUtils.hasText(planNode.getNodeName())){
                    Predicate p5=criteriaBuilder.like(root.get("nodeName").as(String.class), "%" + planNode.getNodeName() + "%");
                    lstPredicates.add(p5);
                }
                Join<Object, Object> planType = plan.join("planType", JoinType.LEFT);
                Dictionary dictionary = dictionaryService.getByCode(PlanType.PROFESSION_TYPE.getCode());
                Dictionary dictionary2 = dictionaryService.getByCode(PlanType.FUNC_TYPE.getCode());
                Predicate p6 = criteriaBuilder.equal(planType.get("id").as(long.class), dictionary.getId());
                Predicate p7 = criteriaBuilder.equal(planType.get("id").as(long.class), dictionary2.getId());
                lstPredicates.add(criteriaBuilder.or(p6,p7));
                Predicate p3 = criteriaBuilder.equal(plan.get("state").as(Integer.class), ApplyState.checkSuccess.getState());
                lstPredicates.add(p3);
                Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
                return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
            }
        };
        Page<PlanNode> pageT =  planMonthRepository.findAll(spec, PageRequest.of(pageIndex, pageSize,  new Sort(Sort.Direction.DESC, "beginDate").and(new Sort(Sort.Direction.ASC, "id"))));
        Pagination<PlanNode> pagination = new Pagination<PlanNode>();
        pagination.setTotal(planMonthRepository.count(spec));
        List<PlanNode> plans = pageT.getContent();
        for(PlanNode planNode2 : plans){
            Company company = orgService.getCompanyById(planNode2.getCompanyId());
            planNode2.setCompanyName(company.getCompanyname());
            Office cOffice = orgService.officeInfo(planNode2.getOfficeId());
            planNode2.setOfficeName(cOffice.getName());
            Post post = orgService.getRoleInfo(planNode2.getPostId());
            planNode2.setPostName(post.getName());
        }
        pagination.setData(plans);
        return pagination;
    }

}
